<script setup>
import { ref, reactive, onMounted } from 'vue'
import { User, Lock, Message, Check, View, Hide } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
// 控制登录方式切换，默认显示密码登录
const loginType = ref('password') // 'password', 'sms'
// 定义数据模型
const LoginData = ref({
  username: '',
  password: '',
  email: '',
  code: '',
  pictureCode: '' // 图形验证码
})
// 验证码倒计时
const countdown = ref(0)
const countdownTimer = ref(null)
// 标记是否可以发送验证码
const canSendCode = ref(true)

// 忘记密码图形验证码相关状态
const resetCaptchaDialogVisible = ref(false) // 控制忘记密码图形验证码弹窗显示
const resetCaptchaImageUrl = ref('') // 存储忘记密码验证码图片URL
const currentResetEmailForCaptcha = ref('') // 存储忘记密码当前邮箱
// 表单引用
const loginFormRef = ref(null)
// 密码可见切换
const passwordVisible = ref(false)
const togglePasswordVisible = () => {
  passwordVisible.value = !passwordVisible.value
}

// 图形验证码弹窗状态
const captchaDialogVisible = ref(false)
const captchaImageUrl = ref('')
const currentEmailForCaptcha = ref('')

// 组件挂载时检查URL参数并自动填充表单
onMounted(() => {
  const email = route.query.email
  const password = route.query.password
  
  if (email && password) {
    // 自动填充邮箱和密码
    LoginData.value.email = email.toString()
    LoginData.value.password = password.toString()
    
    // 自动选择密码登录方式
    loginType.value = 'password'
    
    // 可以选择是否显示提示信息
    // ElMessage.success('注册成功，请点击登录按钮完成登录')
  }
})

// 定义验证规则
// 用户名为1~16位非空字符
// 密码为5~16位非空字符
// 邮箱为非空字符且为邮箱格式
// 验证码为4位非空字符
// 图形验证码为4位数字
//该验证规则只要满足用户和密码或者邮箱及其验证码输入正确就能登录到主页面

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 16, message: '用户名长度为1~16位非空字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5~16位非空字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ],
  pictureCode: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '图形验证码为4位数字', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '图形验证码必须为4位数字', trigger: 'blur' }
  ]
}

//绑定数据，复用注册表单的数据模型
//表单数据校验
//登录函数
import { useTokenStore } from '@/stores/token.ts'
import { useUserStore } from '@/stores/user.ts'
import { userLoginService, sendCodeService, sendLoginCodeService, userCodeLoginService, getUserInfoService, sendResetCodeService, resetPasswordService, getCaptchaService } from '@/api/user.ts'

const tokenStore = useTokenStore();
const userStore = useUserStore();

// 登录方法
const handleLogin = async () => {
  let result;
  
  // 根据登录类型选择不同的API
  if (loginType.value === 'password') {
    // 密码登录
    result = await userLoginService({
      email: LoginData.value.email,
      password: LoginData.value.password
    })
  } else {
    // 验证码登录
    result = await userCodeLoginService({
      email: LoginData.value.email,
      code: LoginData.value.code,
      pictureCode: LoginData.value.pictureCode
    })
  }
  
  if (result.code === 0) {
    ElMessage.success(result.message ? result.message : '登录成功！')
    
    // 将得到的token存储到pinia中
    tokenStore.setToken(result.data.token || result.data)
    
    // 登录成功后立即调用/userInfo接口获取用户信息
    try {
      const userInfo = await getUserInfoService()
      if (userInfo && userInfo.data) {
        // 使用 role 字段，3 为管理员
        const role = Number(userInfo.data.role)
        // 存储用户名、ID和角色
        userStore.setUsername(userInfo.data.username, userInfo.data.id, role)
        // 存储用户头像URL
        if (userInfo.data.avatar) {
          userStore.setAvatar(userInfo.data.avatar)
          console.log('获取用户头像成功:', userInfo.data.avatar)
        }
        console.log('获取用户信息成功，用户名:', userInfo.data.username, '角色:', role)
      } else {
        // 如果获取用户信息失败，使用一个默认用户名
        userStore.setUsername('宝可得用户', undefined, 0)
        console.log('未能获取用户名，使用默认用户名')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      userStore.setUsername('宝可得用户', undefined, 0)
    }
    
    // 登录成功后跳转到Layout界面
    router.push('/layout')
  } else {
    ElMessage.error(result.message ? result.message : '登录失败')
  }
}

// 处理忘记密码图形验证码输入完成
const handleResetCaptchaComplete = async () => {
  if (!resetData.pictureCode || resetData.pictureCode.length !== 4) {
    ElMessage.warning('请输入4位图形验证码')
    return
  }
  
  // 关闭弹窗
  resetCaptchaDialogVisible.value = false
  
  try {
    // 调用发送验证码API，包含邮箱和图形验证码
    const result = await sendResetCodeService(resetData.email, resetData.pictureCode)
    
    // 检查响应是否存在
    if (!result) {
      ElMessage.error('验证码发送失败，服务器无响应')
      // 发送失败时，允许重新发送
      canSendCode.value = true
      return
    }
    
    if (result.code === 0) {
      ElMessage.success('验证码已发送')
      
      // 清空图形验证码
      resetData.pictureCode = ''
      
      // 开始倒计时
      countdown.value = 120
      countdownTimer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(countdownTimer.value)
          // 倒计时结束后，允许再次发送验证码
          canSendCode.value = true
        }
      }, 1000)
    } else {
      ElMessage.error(result.message || '验证码发送失败')
      // 发送失败时，允许重新发送
      canSendCode.value = true
      // 清空图形验证码，让用户重新输入
      resetData.pictureCode = ''
    }
  } catch (error) {
    // 检查是否为429错误
    if (error.response && error.response.status === 429) {
      ElMessage.error('验证码生成过于频繁，5分钟后重试')
    } else {
      ElMessage.error('验证码发送失败，请稍后重试')
    }
    // 发送异常时，允许重新发送
    canSendCode.value = true
    // 清空图形验证码，让用户重新输入
    resetData.pictureCode = ''
  }
}

// 刷新忘记密码图形验证码
const refreshResetCaptchaImage = () => {
  // 添加时间戳避免缓存
  const timestamp = Date.now()
  resetCaptchaImageUrl.value = getCaptchaService(currentResetEmailForCaptcha.value) + '&t=' + timestamp
  console.log('刷新忘记密码图形验证码，新URL:', resetCaptchaImageUrl.value)
}

// 处理忘记密码图形验证码图片加载错误
const handleResetCaptchaImageError = async () => {
  console.error('忘记密码图形验证码图片加载失败，URL:', resetCaptchaImageUrl.value)
  
  // 尝试通过fetch检查具体的错误状态码
  try {
    const response = await fetch(resetCaptchaImageUrl.value, { method: 'HEAD' })
    if (response.status === 429) {
      ElMessage.error('验证码生成过于频繁，5分钟后重试')
    } else {
      ElMessage.error('图形验证码加载失败，请重试')
    }
  } catch (fetchError) {
    // 如果fetch也失败，回退到基本错误消息
    ElMessage.error('图形验证码加载失败，请重试')
  }
}

// 处理忘记密码图形验证码输入
const handleResetCaptchaInput = (value) => {
  // 只允许输入数字
  resetData.pictureCode = value.replace(/[^\d]/g, '')
  
  // 输入满4位自动提交
  if (resetData.pictureCode.length === 4) {
    handleResetCaptchaComplete()
  }
}

// 获取忘记密码图形验证码图片
const getResetCaptchaImage = () => {
  try {
    const captchaUrl = getCaptchaService(currentResetEmailForCaptcha.value)
    resetCaptchaImageUrl.value = captchaUrl
  } catch (error) {
    console.error('获取图形验证码失败:', error)
    ElMessage.error('获取图形验证码失败')
  }
}

// 获取验证码
const getCode = async () => {
  // 如果不能发送验证码，直接返回
  if (!canSendCode.value) {
    return
  }
  
  console.log('当前邮箱值:', LoginData.email)
  console.log('LoginData对象:', LoginData.value)
  console.log('当前登录类型:', loginType.value)
  
  if (!LoginData.value.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  if (!(/^[^\s@]+@[^\s@]+\.[^\s@]+$/).test(LoginData.value.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }
  
  // 先显示图形验证码弹窗
  currentEmailForCaptcha.value = LoginData.value.email
  const timestamp = Date.now()
  captchaImageUrl.value = getCaptchaService(LoginData.value.email) + '&t=' + timestamp
  captchaDialogVisible.value = true
  
  // 监听图片加载错误，设置一个标志来跟踪是否发生了429错误
  setTimeout(() => {
    // 如果图片加载失败，我们会在这里处理
    console.log('图形验证码图片URL已设置:', captchaImageUrl.value)
  }, 100)
}

// 处理图形验证码输入
const handleCaptchaInput = (value) => {
  // 只允许输入数字
  LoginData.value.pictureCode = value.replace(/[^\d]/g, '')
  
  // 输入满4位自动提交
  if (LoginData.value.pictureCode.length === 4) {
    handleCaptchaComplete()
  }
}

// 刷新图形验证码
const refreshCaptchaImage = () => {
  // 添加时间戳避免缓存
  const timestamp = Date.now()
  captchaImageUrl.value = getCaptchaService(currentEmailForCaptcha.value) + '&t=' + timestamp
  console.log('刷新图形验证码，新URL:', captchaImageUrl.value)
}

// 处理图形验证码图片加载错误
const handleCaptchaImageError = async () => {
  console.error('图形验证码图片加载失败，URL:', captchaImageUrl.value)
  
  // 尝试通过fetch检查具体的错误状态码
  try {
    const response = await fetch(captchaImageUrl.value, { method: 'HEAD' })
    if (response.status === 429) {
      ElMessage.error('验证码生成过于频繁，5分钟后重试')
    } else {
      ElMessage.error('图形验证码加载失败，请重试')
    }
  } catch (fetchError) {
    // 如果fetch也失败，回退到基本错误消息
    ElMessage.error('图形验证码加载失败，请重试')
  }
}

// 处理图形验证码输入完成
const handleCaptchaComplete = async () => {
  if (!LoginData.value.pictureCode || LoginData.value.pictureCode.length !== 4) {
    return
  }
  
  // 关闭图形验证码弹窗
  captchaDialogVisible.value = false
  
  // 设置发送状态为false，防止重复点击
  canSendCode.value = false
  
  try {
    // 调用发送登录验证码API，传入邮箱和图形验证码
    const result = await sendLoginCodeService(LoginData.value.email, LoginData.value.pictureCode)
    console.log("result="+result);
    
    // 检查响应是否为空
    if (!result || Object.keys(result).length === 0) {
      ElMessage.error('验证码发送失败，服务器无响应')
      // 发送失败时，允许重新发送
      canSendCode.value = true
      LoginData.value.pictureCode = ''
      return
    }
    
    if (result.code === 0) {
      ElMessage.success('验证码已发送')
      
      // 开始倒计时
      countdown.value = 120
      countdownTimer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(countdownTimer.value)
          // 倒计时结束后，允许再次发送验证码
          canSendCode.value = true
        }
      }, 1000)
    } else {
      ElMessage.error(result.msg || '验证码发送失败')
      // 发送失败时，允许重新发送
      canSendCode.value = true
    }
    
    // 清空图形验证码
    LoginData.value.pictureCode = ''
  } catch (error) {
    // 检查是否为429错误
    if (error.response && error.response.status === 429) {
      ElMessage.error('验证码生成过于频繁，5分钟后重试')
    } else {
      ElMessage.error('验证码发送失败，请稍后重试')
    }
    // 发送异常时，允许重新发送
    canSendCode.value = true
    LoginData.value.pictureCode = ''
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 忘记密码弹窗相关
// 当前步骤
const resetStep = ref(1)
// 控制弹窗显示
const forgotPasswordDialogVisible = ref(false)

// 定义重置密码数据模型
const resetData = reactive({
  email: '',
  code: '',
  password: '',
  confirmPassword: '',
  pictureCode: '' // 图形验证码
})

// 表单引用
const emailFormRef = ref(null)
const passwordFormRef = ref(null)

// 打开忘记密码弹窗
const openForgotPasswordDialog = () => {
  forgotPasswordDialogVisible.value = true
  resetStep.value = 1
  // 重置表单数据
  Object.keys(resetData).forEach(key => {
    resetData[key] = ''
  })
}

// 关闭忘记密码弹窗
const closeForgotPasswordDialog = () => {
  forgotPasswordDialogVisible.value = false
  // 清除定时器
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
  canSendCode.value = true
  countdown.value = 0
}

// 定义验证规则
const resetRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ],
  pictureCode: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '图形验证码长度为4位', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '图形验证码必须为4位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5~16位字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetData.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取重置密码验证码
const getResetCode = async () => {
  // 如果不能发送验证码，直接返回
  if (!canSendCode.value) {
    return
  }
  
  if (!resetData.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(resetData.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }
  
  // 显示图形验证码弹窗
  resetCaptchaDialogVisible.value = true
  currentResetEmailForCaptcha.value = resetData.email
  
  try {
    // 获取图形验证码图片URL
    const timestamp = Date.now()
    resetCaptchaImageUrl.value = getCaptchaService(resetData.email) + '&t=' + timestamp
    console.log('忘记密码图形验证码URL:', resetCaptchaImageUrl.value)
  } catch (error) {
    console.error('获取忘记密码图形验证码失败:', error)
    ElMessage.error('获取图形验证码失败')
    canSendCode.value = true
  }
}

// 验证邮箱和验证码
const verifyResetEmail = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 调用验证码验证接口
        // const result = await verifyCodeService(resetData.email, resetData.code)
         resetStep.value = 2
        //  console.log('验证码验证结果:', result)
        // if (result.code === 0) {
        //   ElMessage.success('邮箱验证成功')
        // } else {
        //   ElMessage.error(result.message || '验证码验证失败')
        // }
      } catch (error) {
        ElMessage.error('验证码验证失败，请重试')
      }
    } else {
      ElMessage.error('请检查输入信息')
    }
  })
}

// 重置密码
const handleResetPassword = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 调用重置密码API
        const result = await resetPasswordService({
          newPwd: resetData.password,
          rePwd: resetData.confirmPassword,
          email: resetData.email,
          code: resetData.code
         
        })
        
        if (result.code === 0) {
          resetStep.value = 3
          ElMessage.success('密码重置成功')
        } else {
          console.log(result.message);
          
          ElMessage.error(result.message || '密码重置失败')
        }
      } catch (error) {
        ElMessage.error('密码重置失败，请重试')
      }
    } else {
      ElMessage.error('请检查输入信息')
    }
  })
}

// 组件卸载时清除定时器
import { onUnmounted } from 'vue'
import { lo } from 'element-plus/es/locales.mjs'
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<template>
  <el-container class="baokede-login-page">
    <!-- 登录区域 -->
    <el-main class="main-content">
      <el-card class="login-box" :body-style="{ padding: '25px' }" shadow="always">
        <!-- 宝可得 Logo -->
        <el-row>
          <el-col :span="24">
            <h1 class="baokede-logo">宝可得</h1>
          </el-col>
        </el-row>
        
        <!-- 登录标签页 -->
        <el-tabs v-model="loginType" class="login-tabs">
          <el-tab-pane label="密码登录" name="password"></el-tab-pane>
          <el-tab-pane label="短信登录" name="sms"></el-tab-pane>
        </el-tabs>

        <!-- 密码登录表单 -->
        <el-form
          v-if="loginType === 'password'"
          ref="loginFormRef"
          :model="LoginData"
          :rules="rules"
          label-position="top"
          class="login-form"
        >
          <el-form-item prop="email">
            <el-input
              v-model="LoginData.email"
              placeholder="请输入邮箱"
              :prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="password" class="password-item">
            <el-input
              v-model="LoginData.password"
              :type="passwordVisible ? 'text' : 'password'"
              placeholder="请输入登录密码"
              :prefix-icon="Lock"
            />
            <div class="password-actions">
              <el-icon
                v-if="LoginData.password && LoginData.password.length > 0"
                class="toggle-pwd"
                @click="togglePasswordVisible"
              >
                <View v-if="!passwordVisible" />
                <Hide v-else />
              </el-icon>
              <el-link type="danger" class="forget-pwd" :underline="false" @click="openForgotPasswordDialog">忘记密码</el-link>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" class="login-button" @click="handleLogin(/*loginFormRef*/)" round>登录</el-button>
          </el-form-item>
          <el-form-item>
            <div class="bottom-links">
              <el-link type="info" :underline="false" class="left-link">
                <el-icon class="icon"><User /></el-icon>忘记账号
              </el-link>
              <el-link type="info" :underline="false" class="right-link" @click="goToRegister">
                <el-icon class="icon"><User /></el-icon>免费注册
              </el-link>
            </div>
          </el-form-item>
        </el-form>

        <!-- 短信登录表单 -->
        <el-form
          v-if="loginType === 'sms'"
          ref="loginFormRef"
          :model="LoginData"
          :rules="rules"
          label-position="top"
          class="login-form"
        >
          <el-form-item prop="email">
            <el-input
              v-model="LoginData.email"
              placeholder="请输入邮箱"
              :prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="code" class="sms-code-item">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input
                  v-model="LoginData.code"
                  placeholder="请输入登录验证码"
                  :prefix-icon="Message"
                />
              </el-col>
              <el-col :span="8">
                <el-button 
                  @click="getCode" 
                  class="get-code-button" 
                  :disabled="countdown > 0 || !canSendCode"
                  :loading="!canSendCode && countdown === 0"
                >
                  {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" class="login-button" @click="handleLogin(loginFormRef)" round>登录</el-button>
          </el-form-item>
          <el-form-item>
            <div class="bottom-links">
              <el-link type="info" :underline="false" class="left-link">
                <el-icon class="icon"><User /></el-icon>忘记账号
              </el-link>
              <el-link type="info" :underline="false" class="right-link" @click="goToRegister">
                <el-icon class="icon"><User /></el-icon>免费注册
              </el-link>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>
  </el-container>
  
  <!-- 图形验证码弹窗 -->
  <el-dialog
    v-model="captchaDialogVisible"
    title="人机验证"
    width="20rem"
    :close-on-click-modal="false"
    @close="() => { LoginData.captcha = ''; canSendCode = true }"
    class="captcha-dialog"
  >
    <div class="captcha-content">
      <div class="captcha-image-container">
        <img 
          :src="captchaImageUrl" 
          alt="图形验证码"
          class="captcha-image"
          @click="refreshCaptchaImage"
          @error="handleCaptchaImageError"
        />
      </div>
      <el-form-item prop="captcha" class="captcha-input-item">
        <el-input
          v-model="LoginData.pictureCode"
          placeholder="请输入图形验证码"
          maxlength="4"
          @input="handleCaptchaInput"
        />
      </el-form-item>
    </div>
  </el-dialog>
  
  <!-- 忘记密码弹窗 -->
  <el-dialog
    v-model="forgotPasswordDialogVisible"
    title="忘记密码"
    width="25rem"
    :close-on-click-modal="false"
    @close="closeForgotPasswordDialog"
    class="forgot-password-dialog"
    :body-style="{ padding: '1.5625rem' }"
  >
    <!-- 进度指示器 -->
    <div class="progress-indicator">
      <div class="progress-step" :class="{ active: resetStep >= 1, completed: resetStep > 1 }">
        <div class="step-circle">
          <el-icon v-if="resetStep > 1"><Check /></el-icon>
          <span v-else>1</span>
        </div>
        <span class="step-text">验证账号</span>
      </div>
      <div class="progress-line" :class="{ active: resetStep >= 2 }"></div>
      <div class="progress-step" :class="{ active: resetStep >= 2, completed: resetStep > 2 }">
        <div class="step-circle">
          <el-icon v-if="resetStep > 2"><Check /></el-icon>
          <span v-else>2</span>
        </div>
        <span class="step-text">重置密码</span>
      </div>
      <div class="progress-line" :class="{ active: resetStep >= 3 }"></div>
      <div class="progress-step" :class="{ active: resetStep >= 3 }">
        <div class="step-circle">
          <span>3</span>
        </div>
        <span class="step-text">完成</span>
      </div>
    </div>

    <!-- 第一步：验证账号 -->
    <div v-if="resetStep === 1" class="step-content">
      <el-form
        ref="emailFormRef"
        :model="resetData"
        :rules="{ email: resetRules.email, code: resetRules.code }"
        label-position="top"
        class="reset-form"
      >
        <el-form-item prop="email">
          <el-input
            v-model="resetData.email"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item prop="code">
          <el-row :gutter="10" align="middle">
            <el-col :span="16">
              <el-input
                v-model="resetData.code"
                placeholder="请输入验证码"
                :prefix-icon="Message"
              />
            </el-col>
            <el-col :span="8" style="display: flex; align-items: center;">
              <el-button
                class="get-code-button"
                @click="getResetCode"
                :disabled="countdown > 0 || !canSendCode"
                :loading="!canSendCode && countdown === 0"
              >
                {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button
            type="danger"
            class="continue-button"
            @click="verifyResetEmail(emailFormRef)"
          >
            下一步
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 第二步：重置密码 -->
    <div v-if="resetStep === 2" class="step-content">
      <el-form
        ref="passwordFormRef"
        :model="resetData"
        :rules="{ password: resetRules.password, confirmPassword: resetRules.confirmPassword }"
        label-position="top"
        class="reset-form"
      >
        <el-form-item prop="password">
          <el-input
            v-model="resetData.password"
            type="password"
            placeholder="请输入新密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="resetData.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="danger"
            class="reset-button"
            @click="handleResetPassword(passwordFormRef)"
          >
            重置密码
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 第三步：完成 -->
    <div v-if="resetStep === 3" class="step-content">
      <div class="success-content">
        <div class="success-icon">
          <el-icon><Check /></el-icon>
        </div>
        <h3 class="success-title">密码重置成功</h3>
        <p class="success-desc">您的密码已经重置成功，请使用新密码登录</p>
                  <el-button
            type="danger"
            class="login-button"
          @click="closeForgotPasswordDialog"
        >
          确定
        </el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 忘记密码图形验证码弹窗 -->
  <el-dialog
    v-model="resetCaptchaDialogVisible"
    title="图形验证码"
    width="22.5rem"
    class="captcha-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="captcha-content">
      <div class="captcha-image-container">
        <img
          v-if="resetCaptchaImageUrl"
          :src="resetCaptchaImageUrl"
          alt="图形验证码"
          class="captcha-image"
          @click="refreshResetCaptchaImage"
          @error="handleResetCaptchaImageError"
        />
        <div v-else class="captcha-loading">加载中...</div>
      </div>
      <div class="captcha-refresh">
        <a href="javascript:void(0)" @click="refreshResetCaptchaImage">看不清？换一张</a>
      </div>
      <el-form-item prop="captcha">
        <el-input
          v-model="resetData.pictureCode"
          placeholder="请输入图形验证码"
          maxlength="4"
          @input="handleResetCaptchaInput"
          class="captcha-input"
        />
      </el-form-item>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.baokede-login-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.main-content {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2.5rem 0.9375rem;
}

.login-box {
  width: 25rem;
  max-width: 100%;
  margin: 0 auto;

  :deep(.el-card__body) {
    padding: 1.5625rem;
  }
}

.baokede-logo {
  text-align: center;
  font-size: 2.25rem;
  font-weight: bold;
  color: #ee5530;
  margin-bottom: 1.5625rem;
  font-family: 'Microsoft YaHei', sans-serif;
}

.login-tabs {
  :deep(.el-tabs__nav-wrap::after) {
    height: 0.0625rem;
    background-color: #e8e8e8;
  }

  :deep(.el-tabs__active-bar) {
    background-color: #ee5530;
    height: 0.125rem;
  }

  :deep(.el-tabs__item) {
    font-size: 1rem;
    color: #333;
    
    &.is-active {
      color: #ee5530;
      font-weight: bold;
    }

    &:hover {
      color: #f07654;
    }
  }

  :deep(.el-tabs__header) {
    margin-bottom: 1.5625rem;
  }

  :deep(.el-tabs__nav) {
    display: flex;
    justify-content: center;
    width: 100%;
  }
}

.login-form {
  .password-item {
    position: relative;
  }

  .password-actions {
    position: absolute;
    right: 0.625rem;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
  .toggle-pwd {
    cursor: pointer;
    color: #999;
  }
  .toggle-pwd:hover {
    color: #666;
  }
  .forget-pwd {
    font-size: 0.75rem;
  }
  .el-input{
    margin: 0.1875rem 0;
  }
  .el-col-8, .el-col-8.is-guttered {
    margin: 0.25rem 0;
  }

  :deep(.el-input__wrapper) {
    background-color: #fff !important;
    
    &.is-focus {
      box-shadow: 0 0 0 0.0625rem #ee5530;
      background-color: #fff !important;
    }
    
    &:hover {
      background-color: #fff !important;
    }
  }

  :deep(.el-input__inner) {
    height: 2.625rem;
    background-color: transparent !important;
    
    &:-webkit-autofill,
    &:-webkit-autofill:hover,
    &:-webkit-autofill:focus {
      -webkit-box-shadow: 0 0 0 62.5rem #fff inset !important;
      -webkit-text-fill-color: #333 !important;
      background-color: #fff !important;
    }
  }
  
  :deep(.el-input) {
    .el-input__wrapper {
      background-color: #fff !important;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 0.9375rem;
  }
   
  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
 
  .login-button {
    width: 100%;
    height: 2.625rem;
    background-color: #ee5530;
    border-color: #ee5530;
    font-size: 1rem;
    
    &:hover, &:focus {
      background-color: #d94825;
      border-color: #d94825;
    }
  }

  .get-code-button {
    width: 100%;
    height: 2.625rem;
    background-color: #f9f9f9;
    color: #333;
    border-color: #e0e0e0;
    
    &:hover {
      background-color: #f0f0f0;
      border-color: #ccc;
    }
    
    &:disabled {
      color: #999;
      cursor: not-allowed;
    }
  }

  .bottom-links {
    display: flex;
    justify-content: space-between;
    margin-top: 0.3125rem;
    width: 100%;
    
    .left-link, .right-link {
      display: flex;
      align-items: center;
      color: #666;
      font-size: 0.8125rem;
      
      &:hover {
        color: #ee5530;
      }
      
      .icon {
        margin-right: 0.3125rem;
      }
    }
  }
}

/* 忘记密码弹窗样式 */
.forgot-password-dialog {
  :deep(.el-dialog__header) {
    padding-bottom: 0.625rem;
    margin-right: 0;
    text-align: center;
    font-weight: bold;
    color: #333;
    font-size: 1.125rem;
  }
  
  :deep(.el-dialog__body) {
    padding: 1.25rem;
  }
  
  :deep(.el-dialog__headerbtn) {
    top: 1.25rem;
  }
}

.progress-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 1.875rem;
  
  .progress-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .step-circle {
      width: 2rem;
      height: 2rem;
      border-radius: 50%;
      background-color: #e0e0e0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
      font-size: 0.875rem;
      font-weight: bold;
      margin-bottom: 0.5rem;
    }
    
    .step-text {
      font-size: 0.75rem;
      color: #999;
    }
    
    &.active {
      .step-circle {
        background-color: #ee5530;
        color: white;
      }
      
      .step-text {
        color: #ee5530;
        font-weight: bold;
      }
    }
    
    &.completed {
      .step-circle {
        background-color: #52c41a;
        color: white;
      }
      
      .step-text {
        color: #52c41a;
        font-weight: bold;
      }
    }
  }
  
  .progress-line {
    width: 3.75rem;
    height: 0.125rem;
    background-color: #e0e0e0;
    margin: 0 0.9375rem;
    margin-bottom: 1.25rem;
    
    &.active {
      background-color: #ee5530;
    }
  }
}

.step-content {
  .reset-form {
    .el-input {
      margin: 0.1875rem 0;
    }
    
    .el-col-8, .el-col-16 {
      margin: 0.25rem 0;
    }
    
    :deep(.el-input__wrapper) {
      background-color: #fff !important;
      
      &.is-focus {
        box-shadow: 0 0 0 0.0625rem #ee5530;
        background-color: #fff !important;
      }
      
      &:hover {
        background-color: #fff !important;
      }
    }

    :deep(.el-input__inner) {
      height: 2.625rem;
      background-color: transparent !important;
      
      &:-webkit-autofill,
      &:-webkit-autofill:hover,
      &:-webkit-autofill:focus {
        -webkit-box-shadow: 0 0 0 62.5rem #fff inset !important;
        -webkit-text-fill-color: #333 !important;
        background-color: #fff !important;
      }
    }
    
    :deep(.el-input) {
      .el-input__wrapper {
        background-color: #fff !important;
      }
    }

    :deep(.el-form-item) {
      margin-bottom: 0.9375rem;
    }
     
    :deep(.el-form-item:last-child) {
      margin-bottom: 0;
    }
    
    .continue-button,
    .reset-button {
      width: 100%;
      height: 2.625rem;
      background-color: #ee5530;
      border-color: #ee5530;
      font-size: 1rem;
      
      &:hover, &:focus {
        background-color: #d94825;
        border-color: #d94825;
      }
    }
    
    .get-code-button {
      width: 100%;
      height: 2.625rem;
      background-color: #f9f9f9;
      color: #333;
      border-color: #e0e0e0;
      
      &:hover {
        background-color: #f0f0f0;
        border-color: #ccc;
      }
      
      &:disabled {
        color: #999;
        cursor: not-allowed;
      }
    }
  }
}

.success-content {
  text-align: center;
  padding: 0.9375rem 0;
  
  .success-icon {
    width: 3.75rem;
    height: 3.75rem;
    border-radius: 50%;
    background-color: #52c41a;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 0.9375rem;
    
    .el-icon {
      font-size: 1.875rem;
      color: white;
    }
  }
  
  .success-title {
    font-size: 1.25rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 0.5rem;
  }
  
  .success-desc {
    color: #666;
    margin-bottom: 0.9375rem;
    font-size: 0.875rem;
  }
  
  .login-button {
    width: 100%;
    height: 2.625rem;
    background-color: #ee5530;
    border-color: #ee5530;
    font-size: 1rem;
    margin-bottom: 0;
    
    &:hover, &:focus {
      background-color: #d94825;
      border-color: #d94825;
    }
  }
}

/* 响应式调整 */
@media (max-width: 48rem) {
  .login-box {
    width: 90%;
  }
  
  .login-form {
    :deep(.el-input__inner),
    .get-code-button,
    .login-button {
      height: 2.375rem;
    }
  }
}

/* 图形验证码弹窗样式 */
.captcha-dialog {
  /* 确保弹窗在页面中央 */
  :deep(.el-dialog__wrapper) {
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 2001;
  }
  
  :deep(.el-dialog) {
    margin: 0 !important;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .captcha-content {
    text-align: center;
    width: 100%;
  }
  
  .captcha-image-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    width: 100%;
  }
  
  .captcha-image {
    width: 120px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    object-fit: contain;
  }
  
  .captcha-input-item {
    margin-bottom: 0;
    width: 200px;
    margin: 0 auto;
  }
  
  /* 响应式调整 */
  @media (max-width: 48rem) {
    :deep(.el-dialog) {
      width: 90% !important;
      max-width: 22.5rem;
    }
    
    .captcha-image {
      width: 100px;
      height: 35px;
    }
    
    .captcha-input-item {
      width: 180px;
    }
  }
}
</style>